package org.example.service;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.params.CursorMarkParams;
import org.example.bean.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service("bookService")
public class BookService {
    @Autowired
    private SolrClient solrClient;
    // 添加数据
    public   void  addBook(Book book){
        try {
            solrClient.addBean(book);
            solrClient.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
    }
    public List<Book> queryBooks(String query){
        SolrQuery solrQuery = new SolrQuery();
        // 设置默认搜索域
        solrQuery.set("df","desc");
        solrQuery.setQuery(query);
        // 高亮显示设置
        solrQuery.setHighlight(true);
        // 添加高亮显示的域
        solrQuery.addHighlightField("name desc");
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        try {
            QueryResponse queryResponse = solrClient.query(solrQuery);
            if (queryResponse == null){
                return  null;
            }
            // 获取高亮
            Map<String, Map<String,List<String>>> hilightMap = queryResponse.getHighlighting();
            // 获取书的列表
            List<Book>  bookList = queryResponse.getBeans(Book.class);
            // 赋值高亮信息
            for (Book book : bookList){
                List<String> list = hilightMap.get(book.getId()).get("desc");
                if(!CollectionUtils.isEmpty(list)){
                    book.setDescription(list.get(0));
                }
                list = hilightMap.get(book.getId()).get("name");
                if(!CollectionUtils.isEmpty(list)){
                    book.setName(list.get(0));
                }
            }
            return  bookList;
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }

}
